// var host = window.location.origin;
var host = 'https://nqct.ip58.lhyw.net'; // 测试地址
var dir = '/youmai';
var signKey = 'U2FsdDSAwqwc34121ss1';
var PAGESIZE = 10; // 分页显示条数
var SEXDINC = ['女', '男'];
var CONSUTATIONTYPE = ['线下就诊', '在线就诊'];
var customUrl = 'https://tb.53kf.com/code/client/96d8f960b261e49515450f8953b044bc5/1';
var appId = 'wxcf59e5dc2c72c1dd';

// 设置toast提示时间
$.toast.prototype.defaults.duration = 1500;

// toast提示
function toast(text){
    $.toast(text, "text");
}

// jquery获取对象参数
$.fn.serializeObject = function(){
    const optionArray = $(this).serializeArray();
    const optionObject = {};
    optionArray.forEach(function(item){
        if(optionObject[item.name] != null){
            if(!optionObject[item.name].push){
                optionObject[item.name] = [optionObject[item.name]];
            }
            optionObject[item.name].push($.trim(item.value));
        }else {
            optionObject[item.name] = $.trim(item.value) || '';
        }
        
    })
    return optionObject
}

// 空值验证
function validEmpty(value, text){
    if(value == null || value === ''){
        toast(text);
        return true
    }
    return false
}

// 手机号验证
function validPhone(phone){
    var reg = /^1[3456789]\d{9}$/;
    if(!reg.test(phone)){
        toast('手机号格式错误');
        return true
    }
    return false
}

// 密码验证
function validPass(password){
    if(/[\da-zA-Z]{8,16}/.test(password)){
        return true
    }else {
        toast('密码为8-16位数字或字母组合');
        return false;
    }
}

// 设置cookie
function setCookie(key, val, time) { 
    if(time === '' || time == undefined) { //time为空
        document.cookie = key + "=" + val + "; path=/"; //设置cookie
    } else { //设置cookie留存时间
        var date = new Date(); //获取当前时间
        date.setTime(date.getTime() + time * 24 * 3600 * 1000); //将date设置为n天以后的时间
        document.cookie = key + "=" + val + ";expires=" + date.toGMTString() + ";path=/"; 
    }
}

// 获取cookie的值
function getCookie(key) {
    /*获取cookie参数*/
    var arrCookie = document.cookie.replace(/[ ]/g, "").split(";"); //获取cookie，去掉空格字符, 转成数组
    var tips; //声明变量tips
    for(var i = 0; i < arrCookie.length; i++) { //使用for循环查找cookie中的tips变量
        var arr = arrCookie[i].split("="); //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
        if(key == arr[0]) { //匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
            tips = arr[1]; //将cookie的值赋给变量tips
            break; //终止for循环遍历
        }
    }
    return tips;
}

// 删除cookie的值
function delCookie(key){
    setCookie(key,'',-10);
}

// 获取URL参数
function getQueryString(name){
    var reg = new RegExp('[?&]' + name + '=([^&]*)(&|$)', 'gi');
    var result =  reg.exec(window.location.search);
    return null != result ? result[1] : null;
}

// 手机号脱敏
function phoneDesensitization(phone){
    return phone ? phone.replace(/^(\d{3})\d*(\d{4})$/, '$1****$2') : '';
}
// 身份证号脱敏
function cardDesensitization(cardId){
    return cardId ? cardId.replace(/^(\d{7})\d*(\d{4})$/, '$1**********$2') : '';
}

// 格式化日期
function format(date){
    if(date == null || date == ''){
        return '';
    }
    // var date = new Date(date),
    //     year = date.getFullYear(),
    //     month = date.getMonth() + 1,
    //     day = date.getDate()
    // return year + '-' + fmt(month) + '-' + fmt(day);
    return date.substr(0, 10);
}
// 格式化日期
function format1(date){
    if(date == null || date == ''){
        return '';
    }
    var date = new Date(date),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate()
    return year + '-' + fmt(month) + '-' + fmt(day);
}

function fmt(d){
    return d < 10 ? '0' + d : d;
}

// http请求封装
var http = function(url, importOptions){
    // 默认参数
    var defaultOption = {
        method: 'POST',
        dataType: 'json',
        hasToken: true,
        noEncry: false,
        loading: false,
        contentType: 'application/json',
        data: {},
        success: function(){},
        fail: function(){},
        complete: function(){}
    };
    // 参数合并
    var options = $.extend({}, defaultOption, importOptions);

    // 显示loading
    if(options.loading){
        $.showLoading();
    }

    // 去掉值为空的参数
    var data = options.data;
    for(var k in data){
        if(data[k] == null || data[k] === ''){
            delete data[k]
        }
    }
    
    // 请求参数添加token
    if(options.hasToken){
        var token = getCookie('token');
        if(!token){
            window.location.href = 'login-code.html'; 
            return false;
        }
        data.token = token;
        data.userId = getCookie('userId');
    }

    // md5加密
    if(!options.noEncry){
        data.timeStamp = new Date().getTime().toString();
        // data.timeStamp = "161846293736";
        data.signKey = signKey;
        dataString = '{'
        Object.keys(data).sort().forEach(function(item, index){
            if(index != 0){
                dataString += ','
            }
            if(typeof data[item] === 'number'){
                dataString += '"' + item + '"' + ':'+ data[item];
            }else {
                dataString += '"' + item + '"' + ':"'+ data[item] +'"';
            }
        })
        dataString += '}';
        data.sign = md5(encodeURIComponent(dataString));
    }
    
    delete data.signKey;
    data = JSON.stringify(options.data);
    
    // 发送请求
    $.ajax({
        url: host + url,
        method: options.method,
        dataType: options.dataType,
        data: data,
        contentType: options.contentType,
        success: function(res){
            if(options.loading){
                $.hideLoading();
            }
            if(res.code !== '01'){
                toast(res.message || res.data)
                if(res.code === '03' && options.hasToken){
                    window.location.href = 'login-code.html'; 
                }
            }else {
                removeNull(res.data)
            }
            options.success(res)
        },
        fail: function(err){
            if(options.loading){
                $.hideLoading();
            }
            toast("网络连接超时，请稍后重试");
            options.fail(err)
        },
        complete: function(res){
            options.complete(res);
            
        }
    })
}

// 处理空值
function removeNull(data, str){
    str = str || '';
    if(data == null || data == 'null' || data == ''){
        return str;
    }
    if(typeof data != 'object'){
        return data;
    }
    for (var k in data){
        if(data[k] == null || data[k] == 'null' || data == ''){
            data[k] = str;
        }
        if(typeof data[k] == 'object'){
            removeNull(data[k])
        }
    }
} 

// 清空倒计时信息
function closePopup(){
    sendStatus = false;
    $('[name=loginMobile]').val('');
    $('[name=checkCode]').val('');
    $('#getCodeBth').html('获取验证码');
    clearTimeout(timer);
}
// 倒计时
var timer;
function countDown($ele, time){
    console.log($ele, time)
    if(--time <= 0){
        sendStatus = false;
        $ele.html('获取验证码');
        return;
    }
    $ele.html(time + 's后重新发送');
    timer = setTimeout(function(){
        countDown($ele, time);
    }, 1000)
}

// 获取验证码
function getCode($ele, phone, type){
    var countDownTime = 60;
    countDown($ele, countDownTime);
    // 请求接口
    http('/user/sendCheckCode', {
        hasToken: false,
        data: {
            loginMobile: phone,
            type: type,
        },
        success: function(res){
            if(res.code === '01'){
                // lhyw.net 是公司测试环境
                if(window.location.host.indexOf('lhyw.net') > -1 || window.location.host.indexOf('localhost') > -1){
                    $.alert(res.data, '验证码');
                }
                // toast('验证码发送成功')
            }
        }
    })
}

// 认证页切换选中项
function changeSelected($target){
    $target.addClass('active').siblings('p').removeClass('active');
}

// 单文件上传
function singleFileUpload(file, success){
    // 请求接口
    var formData = new FormData();
    const xhr = new XMLHttpRequest();	
    formData.append("imgFile",file);
    $.showLoading('上传中..');
    $.ajax({
        url: host + '/userMessage/uploadFile', 
        type:'post',
        data: formData,
        contentType: false, //multipart/form-data
        processData: false,
        success:function(res){
            if(res.code === '01'){
                $.hideLoading();
                success(res.data);
            }else {
                toast(res.message);
            }
        }
    })
}

// 获取上传文件路径
function getFileUrl(file){
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url;
}

// 回到讲堂首页 - 替换历史
function backIndex(delay){
    delay = delay || 0;
    setTimeout(function(){
        window.location.replace(host + dir + '/classroom-index.html');
    }, delay)
}
// 回到讲堂首页 - 添加历史
function backIndex2(delay){
    delay = delay || 0;
    setTimeout(function(){
        window.location.href = host + dir + '/classroom-index.html';
    }, delay)
}
// 获取联动列表html
function getListHtml(data, code, name){
    var html = '';
    data.forEach(function(item, index){
        html +='<p class="' + (index == 0 ? 'active' : '') + '" data-code="' + item[code] + '">' + item[name] + '</p>'
    });
    return html;
}

// 获取无数据html
function getNoDataHtml(txt){
    txt = txt || '没有更多数据了';
    return '<div class="weui-loadmore weui-loadmore_line"><span class="weui-loadmore__tips">' + txt + '</span></div>';
}
// 获取加载更多html
function getLoadMoreHtml(){
    return '<div class="weui-loadmore"><i class="weui-loading"></i><span class="weui-loadmore__tips">正在加载</span></div>';
}
// 获取广告html
function getAdHtml(data){
    var html = '';
    
    if(data.videoId){
        html += '<div class="posRel" data-videoId="' + data.videoId + '">' + 
            '<img src="' + data.file.uploadUrl +'" alt="' + data.name +'">' + 
            '<i class="pub-i-play"></i>';
    }else {
        html += '<div class="posRel">' + 
            '<img src="' + data.file.uploadUrl +'" alt="' + data.name +'">';
    }
    
    html += '</div>';
    return html;
}

// 视频播放
$(document.body).on('click', '[data-videoId]', function (e) {
    var videoId = $(e.currentTarget).attr('data-videoId');
    var backUrl = $(e.currentTarget).attr('data-backUrl');
    if(backUrl){
        window.location.href = backUrl
        return false
    }
    getVideoPlayAuth(videoId)
})

// 获取视频播放凭证
var player2;
function getVideoPlayAuth(videoId){
    $.showLoading('视频加载中...');
    http('/video/getPlayAuth', {
        hasToken: false,
        data: {
            videoId: videoId
        },
        success: function(res){
            // toast('res.code' + res.data.playAuth)
            if(res.code === '01'){
                $('.video.popup').show().find('.cont').hide().html('');
                player2 = new Aliplayer({
                    id: 'player',
                    vid : videoId,
                    playauth : res.data.playAuth,
                    useH5Prism: true,
                    autoplay: true,
                    playsinline: 'true',
                    preload: true,
                    controlBarVisibility: 'click',
                    x5_orientation: 'landscape',
                    x5_type: 'H5',
                    winth: '100%',
                    height: '200px'
                });
                player2.on('ready', function(err){
                    player2.play();
                    player2.fullscreenService.requestFullScreen();
                    setTimeout(function(){
                        $('.video.popup').show().find('.cont').show();
                    },100)
                    $.hideLoading();
                })
            }else {
                $.hideLoading();
            }
        },
        fail: function(){
            $.hideLoading();
        }
    })
}
// 弹窗关闭
$(document.body).on('click', '.popup', function(e){
    $(e.currentTarget).hide();
    if(player2){
        player2.dispose();
    }
})
$(document.body).on('click', '.popup .cont', function(e){
    // e.stopPragatation();
    return false;
})

// 微信一键注册
function getWxopenid() {
    if (code === '' || code == null) {
        var thisUrl = window.location.href;
        thisUrl = encodeURIComponent(thisUrl);
        var theWx = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=';
        var url = theWx + thisUrl + '&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
        window.location.href = url;
    }
}
function getOpenid(){
    var aJson = {
        'jsCode': code,
    };
    $.ajax({
        url: host+'/user/goVxLogin',
        method: 'POST',
        dataType: 'json',
        contentType:'application/json',
        data: JSON.stringify(aJson),
        success: function(res) {
            if (res.code == '01') {
                var data = res.data;
                toast('授权成功')
                if(data.type === '1'){
                    setTimeout(function(){
                        window.location.href = 'login-bind-phone.html?openid=' + data.openid;
                    }, 1000)
                }else {
                    setCookie('token', res.data.token);
                    setCookie('userId', res.data.userId, 1);
                    localStorage.setItem("mobile", res.data.loginMobile);
                    backIndex(1000)
                }
            }else{
                toast(res.message);
            }
        }
    });
}

function xcxConfig() {
    //初始化微信分享参数--开始
    var wxappid = "";
    var timestamp = "";
    var nonceStr = "";
    var signature = "";
    initWxShareParams();
    function initWxShareParams() {
        var requestUrl = window.location.href;
        $.ajaxSetup({
            async: false,
        });
        http('/user/getSign', {
            hasToken: false,
            data: {
                "url": requestUrl
            },
            success: function(res){
                if(res.code === '01'){
                    var iData = res.data;
                    wxappid = iData.appid;
                    timestamp = iData.timestamp;
                    nonceStr = iData.noncestr;
                    signature = iData.signature;

                    //微信分享--开始
                    wx.config({
                        debug: false,
                        appId: wxappid,
                        timestamp: timestamp,
                        nonceStr: nonceStr,
                        signature: signature,
                        jsApiList: [
                            'updateTimelineShareData',
                            'updateAppMessageShareData'
                        ],
                        openTagList: ['wx-open-launch-weapp']
                    });
                }
            }
        })
    }
}

// 跳转微信小程序弹窗关闭
$(document.body).on('click', '.weapp-popup', function(e){
    $(e.currentTarget).css('top', '200%');
})
$(document.body).on('click', '.weapp-popup .cont', function(e){
    e.stopPragatation();
})

function getWeappHtml(url){
    url = url || 'pages/index/index';
    return '<wx-open-launch-weapp class="a" username="gh_3baf85f7018e" path="' + url + '" style="position:absolute;left:0;top:0;width:100%;padding:0;margin:0;opacity:0;z-index:2;">' + 
    '<template> ' + 
        '<style>' + 
            '.btn {width:100vw;height:200vw;}' + 
            '.btn:focus{outline: none;}' + 
        '</style>' + 
        '<button class="btn">跳转小程序</button>' + 
    '</template>' + 
'</wx-open-launch-weapp>'
}

function getNumberHtml(num){
    return num > 99 ? '<span class="number">99</span><span>+</span>' : '<span class="number">' + num + '</span>';
}

// 页面重定向到https
// var ishttps = 'https:' == window.location.protocol ? true: false;
// if(!ishttps){
//     url = window.location.href.replace('http', 'https');
//     window.location.replace(url)
// }